package cn.xmu.j2ee.exp.dao;

import cn.xmu.j2ee.exp.dao.bo.OrderItem;
import cn.xmu.j2ee.exp.dao.bo.Orders;
import cn.xmu.j2ee.exp.mapper.manual.OrderItemMapper;
import cn.xmu.j2ee.exp.mapper.manual.po.OrderItemPo;
import cn.xmu.j2ee.exp.mapper.manual.po.OrdersPo;
import cn.xmu.j2ee.exp.util.BusinessException;
import cn.xmu.j2ee.exp.util.ReturnNo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

import static cn.xmu.j2ee.exp.util.Common.cloneObj;

@Repository
public class OrderItemDao {
    private final Logger logger = LoggerFactory.getLogger(OrderItemDao.class);
    private final OrderItemMapper orderItemMapper;

    @Autowired
    public OrderItemDao(OrderItemMapper orderItemMapper) {
        this.orderItemMapper = orderItemMapper;
    }

    /**
     * 用OrderItemPo对象找OrderItem对象
     * @param  orderId 订单id
     * @return  Orders对象列表，带关联的Orders返回
     */
    public List<OrderItem> retrieveOrderItemByOrderID(Long orderId) throws BusinessException {
        List<OrderItem> orderItemList = new ArrayList<>();
        try{
            List<OrderItemPo> ordersItemPoList = null;
            ordersItemPoList = orderItemMapper.selectOrderItemByOrderId(orderId);
            logger.debug("retrieveOrderItemByOrderID : ordersItemPoList = {}", ordersItemPoList);
            if (null == ordersItemPoList){
                throw new BusinessException(ReturnNo.RESOURCE_ID_NOTEXIST, "orderId不存在");
            }
            OrderItem orderItem=null;
            for(OrderItemPo orderItemPo:ordersItemPoList){
                orderItem=cloneObj(orderItemPo,OrderItem.class);
                orderItemList.add(orderItem);
            }
            logger.debug("findOrdersByID: orderItemList = {}",  orderItemList);
        }
        catch(DataAccessException e){
            logger.error(e.getMessage());
            throw new BusinessException(ReturnNo.INTERNAL_SERVER_ERR, "数据库访问错误");
        }
        return orderItemList;
    }
}
